<template>
  <div id="app" name="app">
    <div class="goTop">
        <i class="el-icon-caret-top" style="font-size: 40px;color: dodgerblue;" @click="goTop"></i>
    </div>
    <el-container>
      <!-- 顶部导航栏 -->
      <div class="topbar">
        <div class="nav">
          <ul>
            <li>
              <el-button type="text" @click="dialogVisible = true" v-show="username == null">登录</el-button>
              <el-button type="text" @click="loginout" v-show="username != null">退出登录</el-button>
            </li>
            <li v-show="username != null">
              欢迎
              <el-popover placement="top" width="180">
                <el-button type="text" slot="reference">{{username}}</el-button>
              </el-popover>
            </li>
            <li>
              <router-link to="/orderList">我的订单</router-link>
            </li>
            <li>
              <router-link to="/collect">我的收藏</router-link>
            </li>
            <li :class="cartProductCount == 1 ? 'shopCart-full' : 'shopCart'">
              <router-link to="/cart">
                <i class="el-icon-shopping-cart-full"></i> 购物车
                <span class="num">({{$store.state.cartProductNum}})</span>
              </router-link>
            </li>
          </ul>
        </div>
      </div>
      <!--顶部导航栏END -->
      <!--登录弹出框-->
      <el-dialog
              title="手机号码登录"
              width="300px" center
              :visible.sync="dialogVisible"
              :before-close="loginDialogClose">
        <p style="color: #666;padding: 5px;">注意:用户未注册,登录自动注册用户</p>
        <el-form status-icon ref="ruleForm" class="demo-ruleForm">
          <el-form-item prop="name" style="margin-bottom: 0px;">
            <el-input type="text" v-model="telephone" prefix-icon="el-icon-user-solid" placeholder="请输入手机号码"></el-input>
          </el-form-item>
          <p style="color: red;">{{telephoneErrorInfo}}</p>
          <div class="so" style="margin-top: 20px;">
            <el-input v-model="verifyCode" placeholder="短信验证码">
              <el-button slot="append" v-show="!show" @click="getLoginVerifyCode">获取验证码</el-button>
              <el-button slot="append" v-show="show">{{count}}秒</el-button>
            </el-input>
            <p style="color: red;">{{codeErrorInfo}}</p>
          </div>
          <el-form-item>
            <el-button
                    size="medium"
                    type="primary"
                    @click="userLogin"
                    style="width:100%;margin-top: 40px;">登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!--登录弹出框end -->
      <!-- 顶栏容器 -->
      <el-header>
        <el-menu
                class="el-menu-demo"
                mode="horizontal"
                active-text-color="#409eff"
                :default-active="activeIndex"
                router
        >
          <div class="logo">
            <router-link to="/">
              <img :src="siteData.logo_path" alt="logo"/>
            </router-link>
          </div>
          <el-menu-item index="/">首页</el-menu-item>
          <el-menu-item index="/products">全部商品</el-menu-item>
          <el-menu-item index="/about">关于我们</el-menu-item>
          <!--搜索框-->
          <div class="so">
            <el-input placeholder="请输入搜索内容" v-model="keywords">
              <el-button slot="append" icon="el-icon-search" @click="searchProductClick"></el-button>
            </el-input>
          </div>
        </el-menu>
      </el-header>
      <!--顶栏容器END -->

      <!--登录模块 -->
      <!--注册模块 -->
      <!--主要区域容器 -->
      <el-main>
        <keep-alive>
          <router-view></router-view>
        </keep-alive>
      </el-main>
      <!-- 主要区域容器END -->
      <!-- 底栏容器 -->
      <el-footer>
        <div class="footer">
          <div class="ng-promise-box">
            <div class="ng-promise">
              <p class="text">
                <a class="icon1" href="javascript:;">7天无理由退换货</a>
                <a class="icon2" href="javascript:;">满99元全场免邮</a>
                <a class="icon3" style="margin-right: 0" href="javascript:;">100%品质保证</a>
              </p>
            </div>
          </div>
          <ul style="display: flex; flex-direction: row; flex-wrap: wrap">
            <li><span style="color: white;">友情链接:</span></li>
            <li v-for="(item,index) in linkData" :key="index" style="margin-left: 20px;">
              <a :href="item.link_path" target="_blank" :title="item.link_name" style="color: white;">{{item.link_name}}</a>
            </li>
          </ul>
          <div class="github">
            <a href="https://gitee.com/dengxchao" target="_blank">
              <div class="github-but"></div>
            </a>
          </div>
          <div class="mod_help">
            <p>
              <router-link to="/">首页</router-link>
              <span>|</span>
              <router-link to="/products">全部商品</router-link>
              <span>|</span>
              <router-link to="/about">关于我们</router-link>
            </p>
            <p class="coty">版权信息:{{siteData.copyright}}</p>
            <p class="coty">备案号:{{siteData.records}}</p>
          </div>
        </div>
      </el-footer>
      <!-- 底栏容器END -->
    </el-container>
  </div>
</template>

<script>

  export default {
    name: "app",
    data() {
      return {
        right: 40,
        bottom: 40,
        activeIndex: '/',
        keywords: '', // 搜索关键字
        dialogVisible: false, // 是否显示登录弹出框,默认不显示
        telephone: null, // 手机号码
        verifyCode: null, // 手机验证码
        resultCode: null, // 后台返回的真实验证码
        telephoneErrorInfo: "", // 保存电话错误信息
        codeErrorInfo: "", // 保存验证码错误信息
        username: null, // 用户名称
        timer: null,  // 倒计时函数
        show: false, // 是否显示倒计时
        count: null, // 倒计时时间
        dialog: false,
        userInfo: {}, // 用户信息
        linkData: [], // 友情链接数据
        siteData: [], // 站点数据
      }
    },
    beforeUpdate() {
      this.activeIndex = this.$route.path;
    },
    created() {
      // console.log(this.$route.path);
      this.activeIndex = this.$route.path;
      this._refreshKeepUserInfo();
      this.getLinkData();
      this.getSiteData();
    },
    methods: {
      // 搜索商品事件(跳转到products商品组件)
      searchProductClick() {
        if (this.keywords == "" || this.keywords == null) {
          window.alert('搜索关键词不能为空');
          return false;
        }
        else {
          this.$router.push({path: '/products', query: {keywords: this.keywords}})
          this.keywords = "";
        }
      },
      // 获取验证码事件
      getLoginVerifyCode() {
        if (this.telephone == "" || this.telephone == null) {
          this.telephoneErrorInfo = "电话号码不能为空";
          return false;
        }
        // 验证手机号码格式
        let pattern = /^1[34578]\d{9}$/;
        if (!pattern.test(this.telephone)) {
          this.telephoneErrorInfo = "手机号码格式不符";
          return false;
        }
        // 发送请求
        this.$axios({
          method: 'post',
          url: this.baseUrl + '/api/v1/login/code',
          data: {
            telephone: this.telephone
          }
        }).then(response => {
          if (response.status == 200) {
            this.resultCode = response.data;
            this.telephoneErrorInfo = "";
            this.codeErrorInfo = "";
            // 进入倒计时
            this._countDown();
          }
        }).catch(error => {

        })
      },
      // 用户登录事件
      userLogin() {
        if (this.telephone == "" || this.telephone == null) {
          this.telephoneErrorInfo = "电话号码不能为空";
          return false;
        }
        // 验证手机号码格式  408950
        let pattern = /^1[34578]\d{9}$/;
        if (!pattern.test(this.telephone)) {
          this.telephoneErrorInfo = "手机号码格式不符";
          return false;
        }
        if (this.verifyCode == "" || this.verifyCode == null) {
          this.codeErrorInfo = "验证码不能为空";
          return false;
        }
        // 发送登录请求
        this._loginRequest();
      },

      // 退出登录
      loginout() {
        let json_userInfo = localStorage.getItem('userInfo');
        let userInfo = JSON.parse(json_userInfo);
        this.$axios({
          method: 'get',
          url: this.baseUrl + '/api/v1/user/loginout',
          headers: {
            'access-token': userInfo.token,
            'telephone': userInfo.telephone
          }
        }).then(response => {
          if (response.data.message = "退出登陆成功" && response.data.status == 200) {
            // 退出登录成功
            this.username = null;
            localStorage.removeItem('userInfo');  // 删除用户数据
            this.loginoutSuccessMessage(); // 提示退出成功
            if (this.$route.path != '/') {
              this.$router.replace('/')
            }

          }
        }).catch(error => {
          if (error.response.status == 403) {
            let errorMessage = error.response.data.message;
            const h = this.$createElement;
            this.$notify({
              title: errorMessage,
              message: h('i', {style: 'color: teal'}, errorMessage)
            });
          }

        })
      },
      // 发送登录ajax请求  登录请求参数 telephone 手机号码 code 自己输入的验证码
      _loginRequest() {
        this.$axios({
          method: 'post',
          url: this.baseUrl + '/api/v1/telephoneLogin',
          data: {
            telephone: this.telephone,
            code: this.verifyCode
          }
        }).then(response => {
          let result = response.data;
          if (result.status == 5000 && result.message == "登陆成功") {
            // 登录成功
            this.telephoneErrorInfo = "";
            this.codeErrorInfo = "";
            this.loginSuccessMessage(result.data.username);
            this.username = result.data.username;
            localStorage.setItem('userInfo',JSON.stringify(result.data));
            // 关闭登录弹出框
            this.dialogVisible = false;
          }
          else {
            // 登录失败, 有一些错误
            this.codeErrorInfo = result.data.message;
          }
        }).catch(error => {
          console.log(error)
        })
      },
      // 登录成功提示消息
      loginSuccessMessage(username) {
        const h = this.$createElement;
        this.$notify({
          title: '登录成功',
          message: h('i', {style: 'color: teal'}, username + '登录成功')
        });
      },
      // 退出登录成功提示消息
      loginoutSuccessMessage() {
        const h = this.$createElement;
        this.$notify({
          title: '退出登录成功',
          message: h('i', {style: 'color: teal'}, '退出登录成功')
        });
      },
      // 倒计时函数
      _countDown() {
        if (!this.timer) {
          // 进入倒计时
          this.count = 60; // 倒计时时间
          this.show = true; // 显示
          this.timer = setInterval(() => {
            if (this.count > 0 && this.count <= 60) {
              this.count --; // 依次递减1
            }
            else {
              // 递减完成,恢复原始数据
              this.count = 60;
              this.timer = null;
              this.show = false;
            }
          }, 1000);
        }
      },
      // 登录弹出框关闭触发
      loginDialogClose(done) {
        if (this.telephoneErrorInfo != "" || this.telephoneErrorInfo != null) {
          this.telephoneErrorInfo = "";
        }
        if (this.codeErrorInfo != "" || this.codeErrorInfo != null) {
          this.codeErrorInfo = "";
        }
        this.$confirm('确认关闭？')
                .then(_ => {
                  done();

                })
                .catch(_ => {});
      },
      // 刷新当前页面,用户数据不改变(只有退出登录才消失)
      _refreshKeepUserInfo() {
          let userInfo = JSON.parse(localStorage.getItem('userInfo'));
          if (userInfo != null) {
              // 存在数据
              this.username = userInfo.username;
          }
          // 解决刷新商品数量为0问题
          let productNum = localStorage.getItem('productNum');
          if (productNum > 0) {
            // 存在商品
            this.$store.commit('setCartProductNum', productNum);
          }
          let selectProductNum = localStorage.getItem('selectProductNum')
          this.$store.commit('setCartSelectProductNum', selectProductNum);
          let productTotalPrice = localStorage.getItem('productTotalPrice')
          this.$store.commit('setCartProductTotalPrice', productTotalPrice);
      },
      // 友情链接数据
      getLinkData() {
        this.$axios.get(this.baseUrl + '/api/v1/user/links')
                .then(response => {
                  this.linkData = response.data.data;
                })
                .catch(error => {
                  console.log(error.response)
                })
      },
      // 站点配置数据
      getSiteData() {
        this.$axios.get(this.baseUrl + '/api/v1/user/site')
                .then(response => {
                  this.siteData = response.data.data;
                  // console.log(response.data.data);
                })
                .catch(error => {
                  console.log(error.response)
                })
      },
      // 返回到顶部
      goTop() {
        // console.log(window.pageYOffset); // 获取浏览器底部到浏览器顶部高度
        // window.scrollTo(0,0);
        var scrollToTop = window.setInterval(function(){
          var pos = window.pageYOffset;
          if ( pos > 0 ) {
            window.scrollTo( 0, pos - 50 ); // how far to scroll on each step
          } else {
            window.clearInterval(scrollToTop);
          }
        }, 15)
      },
    },
    computed: {
      // 计算购物车商品数量
      cartProductCount() {
        if (this.$store.state.cartProductNum > 0 && this.username != null) {
          return 1;
        }
        else {
          return 0;
        }
      }
    }
  }
</script>

<style>
  /* 全局CSS */
  * {
    padding: 0;
    margin: 0;
    border: 0;
    list-style: none;
  }

  .goTop {
    position: fixed;
    width: 40px;
    height: 40px;
    border: 1px solid cornflowerblue;
    right: 40px;
    bottom: 40px;
    cursor: pointer;
    z-index: 999;
  }

  #app .el-header {
    padding: 0;
  }
  #app .el-main {
    min-height: 300px;
    padding: 20px 0;
  }
  #app .el-footer {
    padding: 0;
  }
  a,
  a:hover {
    text-decoration: none;
  }
  /* 全局CSS END */

  /* 顶部导航栏CSS */
  .topbar {
    height: 40px;
    background-color: #3d3d3d;
    margin-bottom: 20px;
  }
  .topbar .nav {
    width: 1225px;
    margin: 0 auto;
  }
  .topbar .nav ul {
    float: right;
  }
  .topbar .nav li {
    float: left;
    height: 40px;
    color: #b0b0b0;
    font-size: 14px;
    text-align: center;
    line-height: 40px;
    margin-left: 20px;
  }
  .topbar .nav .sep {
    color: #b0b0b0;
    font-size: 12px;
    margin: 0 5px;
  }
  .topbar .nav li .el-button {
    color: #b0b0b0;
  }
  .topbar .nav .el-button:hover {
    color: #fff;
  }
  .topbar .nav li a {
    color: #b0b0b0;
  }
  .topbar .nav a:hover {
    color: #fff;
  }
  .topbar .nav .shopCart {
    width: 120px;
    background: #424242;
  }
  .topbar .nav .shopCart:hover {
    background: #fff;
  }
  .topbar .nav .shopCart:hover a {
    color: #ff6700;
  }
  .topbar .nav .shopCart-full {
    width: 120px;
    background: #ff6700;
  }
  .topbar .nav .shopCart-full a {
    color: white;
  }
  /* 顶部导航栏CSS END */

  /* 顶栏容器CSS */
  .el-header .el-menu {
    max-width: 1225px;
    margin: 0 auto;
  }
  .el-header .logo {
    height: 60px;
    width: 189px;
    float: left;
    margin-right: 100px;
  }
  .el-header .so {
    margin-top: 10px;
    width: 300px;
    float: right;
  }
  /* 顶栏容器CSS END */

  /* 底栏容器CSS */
  .footer {
    width: 100%;
    text-align: center;
    background: #2f2f2f;
    padding-bottom: 20px;
  }
  .footer .ng-promise-box {
    border-bottom: 1px solid #3d3d3d;
    line-height: 145px;
  }
  .footer .ng-promise-box {
    margin: 0 auto;
    border-bottom: 1px solid #3d3d3d;
    line-height: 145px;
  }
  .footer .ng-promise-box .ng-promise p a {
    color: #fff;
    font-size: 20px;
    margin-right: 210px;
    padding-left: 44px;
    height: 40px;
    display: inline-block;
    line-height: 40px;
    text-decoration: none;
    /*background: url("./assets/imgs/us-icon.png") no-repeat left 0;*/
  }
  .footer .github {
    height: 50px;
    line-height: 50px;
    margin-top: 20px;
  }
  .footer .github .github-but {
    width: 50px;
    height: 50px;
    margin: 0 auto;
    background: url("./assets/imgs/github.png") no-repeat;
  }
  .footer .mod_help {
    text-align: center;
    color: #888888;
  }
  .footer .mod_help p {
    margin: 20px 0 16px 0;
  }

  .footer .mod_help p a {
    color: #888888;
    text-decoration: none;
  }
  .footer .mod_help p a:hover {
    color: #fff;
  }
  .footer .mod_help p span {
    padding: 0 22px;
  }
  /* 底栏容器CSS END */
</style>
